// lib/models/spu_category.dart
class SpuCategory {
  final String? id; // 数据标识，对应 _id
  final String? owner; // 所有人，系统字段
  final String? image; // 图片 URL
  final List<String>? departmentList; // 所属部门，系统字段
  final List<String>? childCategories; // 子分类列表
  final int? createdAt; // 创建时间，毫秒时间戳
  final String? createBy; // 创建人，系统字段
  final String? updateBy; // 修改人，系统字段
  final String? openid; // 记录创建者，系统字段
  late final String name; // 分类名称
  final List<String>? spus; // 关联的 SPU 列表
  final List<String>? parentCategories; // 父分类列表
  final int? updatedAt; // 更新时间，毫秒时间戳

  SpuCategory({
    this.id,
    this.owner,
    this.image,
    this.departmentList,
    this.childCategories,
    this.createdAt,
    this.createBy,
    this.updateBy,
    this.openid,
    required this.name,
    this.spus,
    this.parentCategories,
    this.updatedAt,
  });

  factory SpuCategory.fromJson(Map<String, dynamic> json) {
    return SpuCategory(
      id: json['_id'] as String,
      owner: json['owner'] as String?,
      image: json['image'] as String?,
      departmentList:
          (json['_departmentList'] as List<dynamic>?)?.cast<String>(),
      childCategories:
          (json['child_cate'] as List<dynamic>?)
              ?.map((item) => (item as Map<String, dynamic>)['_id'] as String)
              .toList() ??
          [],
      createdAt: json['createdAt'] as int? ?? 0,
      createBy: json['createBy'] as String?,
      updateBy: json['updateBy'] as String?,
      openid: json['_openid'] as String?,
      name: json['name'] as String,
      spus:
          (json['spu'] as List<dynamic>?)
              ?.map((item) => (item as Map<String, dynamic>)['_id'] as String)
              .toList() ??
          [],
      parentCategories:
          (json['parent_cate'] as List<dynamic>?)
              ?.map((item) => (item as Map<String, dynamic>)['_id'] as String)
              .toList() ??
          [],
      updatedAt: json['updatedAt'] as int? ?? 0,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      '_id': id,
      'owner': owner,
      'image': image,
      '_departmentList': departmentList,
      'child_cate': childCategories?.map((id) => {'_id': id}).toList(),
      'createdAt': createdAt,
      'createBy': createBy,
      'updateBy': updateBy,
      '_openid': openid,
      'name': name,
      'spu': spus?.map((id) => {'_id': id}).toList(),
      'parent_cate': parentCategories?.map((id) => {'_id': id}).toList(),
      'updatedAt': updatedAt,
    };
  }
}
